from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.urls import reverse
from django.views import generic
from django.views.generic.base import View
from polls.models import Choice
from polls.models import Question


class IndexView(generic.ListView):
    template_name = 'polls/v2/index.html'
    context_object_name = 'questions'

    def get_queryset(self):
        """
        如果是想返回特定的查询，那么就重写get_queryset方法就行
        """
        # return Question.objects.order_by('pub_date')[:10]
        # 因为在 Question 模型中的 Meta 中已经定义了 ordering=【'-pub_data'] 所以可以使用如下
        return Question.objects.all()[:10]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/v2/detail.html'


class ResultView(generic.DetailView):
    model = Question
    template_name = 'polls/v2/result.html'


class VoteView(View):
    """继承Django内置的View试图，然后实现对应的方法即可"""
    @staticmethod
    def post(request, *args, ** kwargs):
        print('v2 vote')
        pk = kwargs.get('pk')
        question = get_object_or_404(Question, pk=pk)
        try:
            selected_choice = question.choice_set.get(pk=request.POST['choice'])
        except (KeyError, Choice.DoesNotExist):
            context = {'error_message': 'You did not select a choice', 'question': question}
            return render(request, 'polls/v2/detail.html', context)
        else:
            selected_choice.votes += 1
            selected_choice.save()
            return HttpResponseRedirect(reverse('polls:v2-polls-result', args=(question.id,)))

